package wsz.consumer;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import wsz.service.MethodService;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wsz
 * @date 2021/12/15 14:13
 **/
public class ConsumerRun {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(20,
            50,
            3,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(1000),
            new ThreadPoolExecutor.AbortPolicy());

    static class MethodRun implements Runnable{
        private String flag;
        private MethodService methodService;
        public MethodRun(String flag, MethodService methodService) {
            this.flag = flag;
            this.methodService = methodService;
        }
        private long current = System.currentTimeMillis();

        @Override
        public void run() {
            try {
                do {
                    methodService.methodA(flag);
                    methodService.methodB(flag);
                    methodService.methodC(flag);
                    // 持续调用2分钟
                } while (System.currentTimeMillis() - current < 1000*60*2);
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception{
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("dubbo-consumer.xml");
        context.start();
        MethodService methodService = context.getBean(MethodService.class);
        System.in.read();
        System.out.println("开始调用provider");

        // 使用20个线程，持续调用2分钟
        for (int i = 0; i < 20; i++) {
            executor.execute(new MethodRun("executor" + i, methodService));
        }
    }
}
